package com.by.yz.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.toolbox.NetworkImageView;
import com.bumptech.glide.Glide;
import com.by.yz.App;
import com.by.yz.R;
import com.by.yz.activity.base.BaseActivity;
import com.by.yz.custom.CircleNetworkImageView;
import com.by.yz.custom.TechnologyTeamDividerItemDecoration;
import com.by.yz.entity.AskBean;
import com.by.yz.entity.Doctorbean;
import com.by.yz.entity.UserTest;
import com.by.yz.loginUtil.QustionRESFul;
import com.by.yz.loginUtil.UserRESTFul;
import com.by.yz.util.ToJSonObject;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by John on 2016/10/13.
 */
public class QuickAnswerActivity extends BaseActivity{

    private RecyclerView resultListview;
    List<AskBean> datas=new ArrayList<AskBean>();
    SimpleStringRecyclerViewAdapter simpleStringRecyclerViewAdapter;
    AskBean askBean;
    String nickname="";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.quick_answer);
        simpleStringRecyclerViewAdapter=new SimpleStringRecyclerViewAdapter(this,datas);
        initView();
        initDatas();
    }

    @Override
    public void onRestart(){
        super.onRestart();
        datas.clear();
        initDatas();
        initView();
    }
    private void initDatas(){
        if(isNetworkAvailable(QuickAnswerActivity.this)){
            QustionRESFul qustionRESFul = new QustionRESFul();
            qustionRESFul.getQuestion(new QustionRESFul.MyGetCallBack() {
                @Override
                public void error(String error) {
                    Log.e("hj", "更新失败" + error);
                }
                @Override
                public void ok(JSONArray response) throws JSONException {
                    for (int i = 0; i < response.length(); i++) {
                        JSONObject jsonObject = response.getJSONObject(i);
                        askBean = ToJSonObject.jsonToBean(jsonObject.toString(), AskBean.class);
                        if(!askBean.getFlag()) {
                            datas.add(askBean);
                        }
                    }
                    simpleStringRecyclerViewAdapter .notifyDataSetChanged();

                }
            });
        }else{
            //无网络连接情况
            new AlertDialog.Builder(QuickAnswerActivity.this)
                    .setTitle("提示!")
                    .setIcon(android.R.drawable.ic_dialog_info)
                    .setMessage("检测到您还没开启网络，请开启")
                    .setNegativeButton("取消", null)
                    .setPositiveButton("开启",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog,
                                                    int which) {
                                    startActivity(new Intent(
                                            Settings.ACTION_WIRELESS_SETTINGS));// 进入无线网络配置界面
                                }
                            }).show();
        }

    }

    private void initView() {
        setToolbarTitle("快速解答");
        resultListview=(RecyclerView) findViewById(R.id.quick_answer);
        resultListview.setLayoutManager(new LinearLayoutManager(resultListview.getContext()));
        resultListview.setAdapter(simpleStringRecyclerViewAdapter );
        resultListview.addItemDecoration(new TechnologyTeamDividerItemDecoration(this,TechnologyTeamDividerItemDecoration.VERTICAL_LIST));

        //final String seriesName = getIntent().getStringExtra("searchString");
    }

    public static class SimpleStringRecyclerViewAdapter
            extends RecyclerView.Adapter<SimpleStringRecyclerViewAdapter.ViewHolder> {

        private final TypedValue mTypedValue = new TypedValue();
        private int mBackground;
        private List<AskBean> mValues;



        public static class ViewHolder extends RecyclerView.ViewHolder {
            public AskBean tt;

            public final View mView;
            public final CircleNetworkImageView mImageView;
            public final TextView askName;
            public final TextView askTime;
            public final TextView question;


            public ViewHolder(View view) {
                super(view);
                mView = view;
                mImageView = (CircleNetworkImageView) view.findViewById(R.id.answer_image);
                askName = (TextView) view.findViewById(R.id.askName);
                askTime = (TextView) view.findViewById(R.id.ask_time);
                question = (TextView) view.findViewById(R.id.question);
            }

//            @Override
//            public String toString() {
//                return super.toString() + " '" + mTextView.getText();
//            }
        }

        public AskBean getValueAt(int position) {
            return mValues.get(position);
        }

        public SimpleStringRecyclerViewAdapter(Context context, List<AskBean> items) {
            context.getTheme().resolveAttribute(R.attr.selectableItemBackground, mTypedValue, true);
            mBackground = mTypedValue.resourceId;
            mValues = items;
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.quick_answer_item, parent, false);
            // view.setBackgroundResource(mBackground);
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(final ViewHolder holder, int position) {
            holder.tt = mValues.get(position);
            holder.askName.setText(mValues.get(position).getCreater());
            holder.mImageView.setDefaultImageResId(R.mipmap.headimg);
            holder.mImageView.setErrorImageResId(R.mipmap.headimg_error);
            final String creater=mValues.get(position).getCreater();
            new Thread(){
                @Override
                public void run(){
                    UserRESTFul userRESTFul=new UserRESTFul();
                    userRESTFul.getUser(creater, new UserRESTFul.UserPOSTCallBack() {
                        @Override
                        public void ok(JSONObject response) throws JSONException {
                            UserTest userTest;
                            JSONObject jsonObject=response;
                            userTest=ToJSonObject.jsonToBean(jsonObject.toString(),UserTest.class);
                            holder.askName.setText(userTest.getnickName());
                            String image = userTest.getHeadimg();
                            try {
                                holder.mImageView.setImageUrl(image, App.imageLoader);
                                Log.e("image","image");
                            }catch(Exception e) {
                                Log.e("image","null");
                                holder.mImageView.setImageUrl("http://img2.hao661.com/uploads/allimg/c150515/1431E91Z5M10-2194c1.jpg",App.imageLoader);
                            }
                        }
                        @Override
                        public void error(String response) {
                            Log.e("PCF-user-error","获取用户表失败"+response);
                        }
                    });
                }
            }.start();
            String s= mValues.get(position).getTitle().replaceAll("T", " ");
            String s1 = s.substring(0,16);
            holder.askTime.setText(s1);
            holder.question.setText(mValues.get(position).getContent());
            holder.mView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Context context = v.getContext();
                    Intent intent = new Intent(context, QuestionDetail.class);
//                    intent.putExtra(CheeseDetailActivity.EXTRA_NAME, holder.mBoundString);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("question",holder.tt);
                    intent.putExtras(bundle);
                    context.startActivity(intent);
                }
            });

            Glide.with(holder.mImageView.getContext())
                    .load(mValues.get(position).getQuestion_image())
                    .fitCenter()
                    .into(holder.mImageView);
        }

        @Override
        public int getItemCount() {
            return mValues.size();
        }
    }
    /*
 * 判断是否有网络
 */
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm == null) {
            return false;
        } else {
            // 如果仅仅是用来判断网络连接　　　　　　
            // 则可以使用 cm.getActiveNetworkInfo().isAvailable();
            NetworkInfo networkInfo = cm.getActiveNetworkInfo();
            if (networkInfo != null) {
                Log.e("hj","isNetworkAvailable - 是否有网络： "+ networkInfo.isAvailable());
                return true;
            } else {
                Log.e("hj", "isNetworkAvailable - 完全没有网络！");
                return false;
            }
        }
    }
}